import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// 请求拦截器

service.interceptors.request.use(
  config => {
  // do something before request is sent
    if (store.getters.token && !config.url.includes('/auth/local/register')) {
      const loginTime = localStorage.getItem('loginTime')
      const timeOut = 1000 * 60 * 60 * 2
      const newTime = Date.now()
      const isTimeOut = newTime - loginTime > timeOut
      if (isTimeOut) {
        Message.warning({
          message: '登录超时，请重新登录',
          center: true
        })
        store.dispatch('user/logout')
        return Promise.reject(new Error('登录超时'))
      }
      // 设置非注册接口时，加入token
      config.headers.Authorization = 'Bearer ' + store.getters.token
    }
    return config
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
  const { status, data } = response
  if (status === 200) {
    return data
  }
},
error => {
  console.dir(error) // for debug
  if (error.response && error.response.status === 404) {
    Message.error({
      message: error.message,
      center: true
    })
  } else if (error.response && error.response.status === 400) {
    Message.error({
      message: error.response.data.data[0].messages[0].message || error.response.data.data[0].messages[0].id,
      center: true
    })
  } else if (error.response && error.response.status === 401) {
    Message.error({
      message: '登录失效,请重新登录',
      center: true
    })
    store.dispatch('user/logout')
  } else {
    Message.error({
      message: error.message,
      center: true
    })
  }
  return Promise.reject(error)
})

export default service
